<template>
  <div class="overview">
    <Selector
      v-model:current-tab="currentTab"
      v-model:selectTime="selectTime"
      v-model:classId="classId"
      v-model:currentGradeNum="currentGradeNum"
      v-model:currentGradeId="currentGradeId"
      is-knowledge
      @changeSubject="selectObj.subject_id = $event"
      class="header"
    />

    <div class="container" :class="{ 'atlas-mode': !isShowList }">
      <div class="filter-bar">
        <Tabs v-model:current-tab="currentTab" v-if="!isShowList" />
        <transition name="fade-slide" appear mode="out-in">
          <div
            v-if="isCompare || isShowList"
            class="operator"
            :class="{ 'is-graph-operator': isCompare && !isShowList }"
          >
            <template v-if="isCompare || isShowList">
              <button
                class="back-btn"
                @click="isShowList = false"
                v-if="isShowList"
              >
                返回图谱分析
              </button>
              <div class="compare" :class="{ 'graph-compare': !isShowList }">
                <div class="text">对比</div>
                <el-select
                  v-model="compareValue"
                  placeholder="请选择对比"
                  @change="handleSelectChange"
                >
                  <el-option
                    v-for="compare in compareOption"
                    :key="compare.value"
                    :label="compare.label"
                    :value="compare.value"
                  />
                </el-select>
              </div>
            </template>
          </div>
        </transition>
      </div>

      <KnowledgeTable
        v-if="isShowList"
        @toDetail="toDetail"
        :activeTab="currentTab"
        :tableData
        :compareLabel
        :isLoading
      />
      <template v-if="!isShowList">
        <Showroom
          v-if="!switchD3Graph"
          @toDetail="toDetail"
          v-model:isCompare="isCompare"
          v-model:currentTabIndex="currentTabIndex"
          v-model:isShowList="isShowList"
          :activeTab="currentTab"
          :currentGradeNum
          :subjectId
          :selectObj
          :selectTime
          :knowledgeTree
          :classId
          :isLoading
          :nodeLookup
          :compareLabel
        ></Showroom>
        <GraphAnalyze
          v-if="switchD3Graph"
          @toDetail="toDetail"
          v-model:isCompare="isCompare"
          v-model:currentTabIndex="currentTabIndex"
          v-model:isShowList="isShowList"
          :activeTab="currentTab"
          :currentGradeNum
          :subjectId
          :selectObj
          :selectTime
          :knowledgeTree
          :classId
          :isLoading
          :nodeLookup
          :compareLabel
        />
      </template>

      <div class="options-list" v-if="!isCompare">
        <div
          class="options-item"
          v-for="(item, index) in pointOptions"
          :key="index"
        >
          <div
            class="item-color"
            :style="`background-color: ${item.color};`"
          ></div>
          <span>{{ item.rate }}</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, watch, reactive, computed, provide } from 'vue'
import router from '@/router'
import dayjs from 'dayjs'

import { computedStageId } from '@/utils'
import { getKnowledgeTree } from '@/apis/target-boost'
import { debounce } from 'lodash'

import KnowledgeTable from '@/views/target-boost/components/KnowledgeTable.vue'
import Selector from '@/components/Selector.vue'
import Tabs from './AnalyzeTabs.vue'
import GraphAnalyze from './GraphAnalyze.vue'
import Showroom from '@/views/showroom/Showroom.vue'

import { storeToRefs } from 'pinia'
import { useKnowledgeStore } from '@/stores/knowledge-store'
import { useAuthStore } from '@/stores'

const authStore = useAuthStore()

// const isShowroom = computed(() => {
//   const { userId } = authStore.userInfo
//   return userId === '3111685730978099' || userId === '3436087301323703'
// })

const switchD3Graph = ref(false)
const onSwitchD3Graph = () => {
  switchD3Graph.value = !switchD3Graph.value
}

provide('onSwitchD3Graph', onSwitchD3Graph)

// 图例
const pointOptions = [
  {
    color: '#19783B',
    rate: '95%~100%'
  },
  {
    color: '#EC6941',
    rate: '60%~85%'
  },
  {
    color: '#32B16C',
    rate: '85%~95%'
  },
  {
    color: '#D92325',
    rate: '0%~60%'
  },
  {
    color: '#B3D465',
    rate: '80%~85%'
  },
  {
    color: '#CCCCCC',
    rate: '未学习'
  }
]
// 对比
const compareValue = ref('0')
const compareLabel = ref('年级平均')

const compareOption = [
  {
    value: '0',
    label: '年级平均'
  },
  {
    value: '1',
    label: '年级前10%'
  },
  {
    value: '3',
    label: '年级前30%'
  }
]
const subjectId = ref(2)
// 选择的参数改变，传给图谱组件
const selectObj = ref({
  subject_id: subjectId.value,
  compare: 0
})

const handleSelectChange = value => {
  isLoading.value = true
  selectObj.value.compare = value

  // 查找选中值对应的label
  const selectedOption = compareOption.find(option => option.value === value)

  if (selectedOption) {
    compareLabel.value = selectedOption.label
  } else {
    compareLabel.value = ''
  }
}

const {
  classId,
  currentGradeNum,
  currentGradeId,
  selectedTime: selectTime,
  classType
} = storeToRefs(authStore)

const isShowList = ref(false)
const currentTab = ref('right-rate')
const isCompare = ref(false)
const currentTabIndex = ref(0)

const tableData = ref([])

const knowledgeStore = useKnowledgeStore()

const toDetail = (scoped, record) => {
  console.log(scoped, record)
  if (!knowledgeStore.knowledgeTree) {
    knowledgeStore.knowledgeTree = JSON.parse(
      JSON.stringify(knowledgeTree.value)
    )
  }
  let query = {
    name: scoped ? scoped.name : knowledgeStore.knowledgeTree.name,
    school_id: authStore.userInfo.school_id,
    start_time: selectTime.value[0] || dayjs('2021-01-01').unix(),
    end_time: selectTime.value[1] || dayjs().unix(),
    class_type: +classType.value,
    subject_id: selectObj.value.subject_id,
    class_id: classId.value,
    grade_num: currentGradeNum.value,
    grade_id: currentGradeId.value,
    stage_id: computedStageId(currentGradeNum.value),
    knowledge_id: scoped ? scoped.id : knowledgeStore.knowledgeTree.id
  }
  if (record) {
    query.task_id = record.task_id
    query.task_name = record.task_name
    query.origin_task_id = record.origin_task_id
  }
  if (scoped) {
    // 记录选中的知识点树
    knowledgeStore.setKnowledgeTree(scoped)

    let knowledgePointArr = [scoped.id]
    const newIdArr = handleKnowledgeArr(scoped.children)
    knowledgePointArr = knowledgePointArr.concat(newIdArr)
    console.log(knowledgePointArr, 'knowledgePointArr')
    knowledgeStore.setKnowledgeIds(knowledgePointArr)
    console.log(scoped.row, 'scoped.row')
  }

  // 构建URL
  const route = router.resolve({
    name: 'details',
    query: query
  })

  // 在新标签页中打开URL
  window.open(route.href, '_blank')
}

function handleKnowledgeArr(children) {
  let idArr = []
  if (children !== undefined && children !== null && children.length !== 0) {
    children.forEach(item => {
      idArr.push(item.id)
      if (
        item.children !== undefined &&
        item.children !== null &&
        item.children.length !== 0
      ) {
        const newIdArr = handleKnowledgeArr(item.children)
        idArr = idArr.concat(newIdArr)
      }
    })
  }
  return idArr
}

const knowledgeTree = ref(null)

// 用于存储节点的查找表
const nodeLookup = reactive({})

// 递归处理树形结构数据，删除空的 children 属性，并添加 parentId 属性，好拿到父节点，这个函数可以优化
const operateTree = (data, parentId = null) => {
  if (Array.isArray(data)) {
    data.forEach(node => {
      // 设置 parentId 并递归处理子节点
      node.parentId = parentId
      nodeLookup[node.id] = node // 将节点添加到查找表中
      // 如果没有子节点，删除空的 children 属性
      if (!node.children || !node.children.length) {
        delete node.children
      } else {
        operateTree(node.children, node.id)
      }
    })
  } else {
    // 设置 parentId 并递归处理子节点
    data.parentId = parentId
    nodeLookup[data.id] = data // 将节点添加到查找表中
    // 如果没有子节点，删除空的 children 属性
    if (!data.children || !data.children.length) {
      delete data.children
    } else {
      operateTree(data.children, data.id)
    }
  }
}

const isLoading = ref(false)
const catchKnowledge = []

const getKnowledgeTreeFn = async () => {
  isLoading.value = true
  const params = {
    school_id: authStore.userInfo.school_id,
    class_id: classId.value.toString(),
    class_type: classType.value,
    grade_id: currentGradeNum.value,
    subject_id: selectObj.value.subject_id,
    stage_id: computedStageId(currentGradeNum.value),
    compare: +selectObj.value.compare,
    start_time: +selectTime.value?.[0] || dayjs('2021-01-01').unix(),
    end_time: +selectTime.value?.[1] || dayjs().unix()
  }

  const res = await getKnowledgeTree(JSON.stringify(params))

  operateTree(res.data)
  // 缓存数据
  catchKnowledge[selectObj.value.compare] = res.data
  knowledgeTree.value = res.data

  tableData.value = [res.data]
  // 隐藏动画
  isLoading.value = false
}
const debouncedGetKnowledgeTreeFn = debounce(getKnowledgeTreeFn, 1000)
// watch(isCompare, async () => {
//   if (!isCompare.value) {
//     knowledgeTree.value = catchKnowledge[0]
//     tableData.value = [catchKnowledge[0]]
//   } else {
//     knowledgeTree.value = catchKnowledge[selectObj.value.compare]
//     tableData.value = [catchKnowledge[selectObj.value.compare]]
//   }
// })

const { nowGlobalSubjectId } = storeToRefs(authStore)

watch(
  () => [
    currentGradeNum.value,
    classId.value,
    nowGlobalSubjectId.value,
    selectTime.value,
    selectObj.value,
    authStore.userInfo.school_id
  ],
  async (oldVals, newVals) => {
    console.log(oldVals, newVals)
    // 暂时先去掉缓存优化，没时间想
    // 检查除了 selectObj.value 的其他值是否相同
    // const otherValuesEqual = oldVals.slice(0, 4).every((val, index) => {
    //   console.log(oldVals[2], newVals[2])
    //   return val === newVals[index] && oldVals[5] === newVals[5]
    // })
    // // 如果相同，直接使用缓存数据
    // if (
    //   otherValuesEqual &&
    //   oldVals[4].compare === newVals[4].compare &&
    //   catchKnowledge[newVals[4].compare]
    // ) {
    //   const newData = JSON.parse(
    //     JSON.stringify(catchKnowledge[newVals[4].compare])
    //   )
    //   operateTree(newData)
    //   knowledgeTree.value = newData
    //   tableData.value = [newData]

    //   return
    // }
    if (
      !currentGradeNum.value ||
      !classId.value ||
      !authStore.userInfo.school_id
    ) {
      console.log(authStore.userInfo.school_id)
      return
    }
    await debouncedGetKnowledgeTreeFn()
  },
  {
    deep: true
  }
)
</script>
<style lang="less" scoped>
.overview {
  position: relative;
  height: calc(100% - 50px);

  .header {
    position: absolute;
    top: 0;
    right: 0;
    transform: translateY(-45px);
    display: flex;
    justify-content: space-between;
  }
}

.container {
  padding: 22px 22px 0;
  height: calc(100% - 12px);
  background-color: #fff;
  position: relative;

  .content {
    height: calc(100% - 50px);

    .mark {
      display: inline-block;
      width: 10px;
      height: 10px;
      margin-right: 5px;
      border-radius: 50%;
    }
  }

  .options-list {
    position: absolute;
    bottom: calc(10vh - 39px);
    left: 61%;
    display: grid;
    grid-template-rows: 1fr 1fr;
    grid-template-columns: 1fr 1fr;
    gap: 7px;
    width: 222.5px;
    transform: scale(0.9);
    transform-origin: bottom;

    .options-item {
      display: flex;
      gap: 10px;
      font-weight: 400;
      font-size: 14px;
      align-items: center;

      .item-color {
        width: 16px;
        height: 16px;
        border-radius: 50%;
      }
    }
  }
}

.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;

  .operator {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    &.is-graph-operator {
      position: absolute;
      top: 22px;
    }

    .back-btn {
      width: 150px;
      height: 30px;
      font-size: 16px;
      border: 1px solid @color-brand-regular;
      color: @color-brand-regular;
      background-color: #fff;
      cursor: pointer;
    }
  }

  .compare {
    display: flex;
    align-items: center;
    position: relative;

    &.graph-compare {
      position: absolute;
      right: 0;
    }

    .text {
      flex: 0 0 auto;
      box-sizing: border-box;
      border: 1px solid @color-brand-regular;
      border-right: 0;
      width: 60px;
      height: 30px;
      background-color: #fff;
      line-height: 30px;
      text-align: center;
      font-size: 16px;
      color: @color-brand-regular;
    }

    .el-select {
      width: 180px;

      :deep(.el-select__wrapper) {
        box-shadow: none;
        border: 1px solid @theme-color;
        border-radius: 0;
        height: 30px;
        min-height: unset;
      }

      :deep(.el-select__selected-item) {
        text-align: center;
        font-size: 16px;
        color: @theme-color;
      }
    }
  }
}

.atlas-mode {
  position: relative;
  padding: 0;
  height: 100%;
  background-color: transparent;

  .tab-container {
    position: absolute;
    top: 0;
    width: 100%;
    display: flex;
    justify-content: center;
  }

  .filter-bar {
    position: absolute;
    top: 22px;
    left: 22px;
    right: 432px;
    z-index: 2;
  }

  .content {
    height: 100%;
  }
}
</style>
